{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "47E90C81C14A46A6880F8F0569D54299",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# 线性回归\n",
    "主要内容包括：\n",
    "\n",
    "线性回归的基本要素\n",
    "线性回归模型从零开始的实现\n",
    "线性回归模型使用pytorch的简洁实现"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "F9068A9D99434C76860365C5CBDF1B01",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# 线性回归的基本要素\n",
    "**模型**\n",
    "为了简单起见，这里我们假设价格只取决于房屋状况的两个因素，即面积（平方米）和房龄（年）。接下来我们希望探索价格与这两个因素的具体关系。线性回归假设输出与各个输入之间是线性关系:\n",
    "\n",
    "price=warea⋅area+wage⋅age+b\n",
    " \n",
    "**数据集**\n",
    "我们通常收集一系列的真实数据，例如多栋房屋的真实售出价格和它们对应的面积和房龄。我们希望在这个数据上面寻找模型参数来使模型的预测价格与真实价格的误差最小。在机器学习术语里，该数据集被称为训练数据集（training data set）或训练集（training set），一栋房屋被称为一个样本（sample），其真实售出价格叫作标签（label），用来预测标签的两个因素叫作特征（feature）。特征用来表征样本的特点。\n",
    "\n",
    "**损失函数**\n",
    "在模型训练中，我们需要衡量价格预测值与真实值之间的误差。通常我们会选取一个非负数作为误差，且数值越小表示误差越小。一个常用的选择是平方函数。 它在评估索引为  i  的样本误差的表达式为\n",
    "\n",
    "l(i)(w,b)=12(y^(i)−y(i))2,\n",
    " \n",
    "L(w,b)=1n∑i=1nl(i)(w,b)=1n∑i=1n12(w⊤x(i)+b−y(i))2.\n",
    " \n",
    "**优化函数 - 随机梯度下降**\n",
    "当模型和损失函数形式较为简单时，上面的误差最小化问题的解可以直接用公式表达出来。这类解叫作解析解（analytical solution）。本节使用的线性回归和平方误差刚好属于这个范畴。然而，大多数深度学习模型并没有解析解，只能通过优化算法有限次迭代模型参数来尽可能降低损失函数的值。这类解叫作数值解（numerical solution）。\n",
    "\n",
    "在求数值解的优化算法中，小批量随机梯度下降（mini-batch stochastic gradient descent）在深度学习中被广泛使用。它的算法很简单：先选取一组模型参数的初始值，如随机选取；接下来对参数进行多次迭代，使每次迭代都可能降低损失函数的值。在每次迭代中，先随机均匀采样一个由固定数目训练数据样本所组成的小批量（mini-batch） B ，然后求小批量中数据样本的平均损失有关模型参数的导数（梯度），最后用此结果与预先设定的一个正数的乘积作为模型参数在本次迭代的减小量。\n",
    "\n",
    "(w,b)←(w,b)−η|B|∑i∈B∂(w,b)l(i)(w,b)\n",
    " \n",
    "学习率:  η 代表在每次优化中，能够学习的步长的大小\n",
    "批量大小:  B 是小批量计算中的批量大小batch size\n",
    "\n",
    "**总结一下，优化函数的有以下两个步骤：**\n",
    "\n",
    "(i)初始化模型参数，一般来说使用随机初始化；\n",
    "(ii)我们在数据上迭代多次，通过在负梯度方向移动参数来更新每个参数。\n",
    "矢量计算\n",
    "在模型训练或预测时，我们常常会同时处理多个数据样本并用到矢量计算。在介绍线性回归的矢量计算表达式之前，让我们先考虑对两个向量相加的两种方法。\n",
    "\n",
    "向量相加的一种方法是，将这两个向量按元素逐一做标量加法。\n",
    "向量相加的另一种方法是，将这两个向量直接做矢量加法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "id": "97850C454D4F481D82C10BB1E23596B8",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import time\n",
    "\n",
    "# init variable a, b as 1000 dimension vector\n",
    "n = 1000\n",
    "a = torch.ones(n)\n",
    "b = torch.ones(n)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "id": "D744FC2EEBE34A32868B55D3D2B7613B",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# define a timer class to record time\n",
    "class Timer(object):\n",
    "    \"\"\"Record multiple running times.\"\"\"\n",
    "    def __init__(self):\n",
    "        self.times = []\n",
    "        self.start()\n",
    "\n",
    "    def start(self):\n",
    "        # start the timer\n",
    "        self.start_time = time.time()\n",
    "\n",
    "    def stop(self):\n",
    "        # stop the timer and record time into a list\n",
    "        self.times.append(time.time() - self.start_time)\n",
    "        return self.times[-1]\n",
    "\n",
    "    def avg(self):\n",
    "        # calculate the average and return\n",
    "        return sum(self.times)/len(self.times)\n",
    "\n",
    "    def sum(self):\n",
    "        # return the sum of recorded time\n",
    "        return sum(self.times)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "DC245B3ED97340F28732B5F3DC1D41FE",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "现在我们可以来测试了。首先将两个向量使用for循环按元素逐一做标量加法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "id": "065FABF0519B497C8B1E4EADE98C5080",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'0.01071 sec'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "timer = Timer()\n",
    "c = torch.zeros(n)\n",
    "for i in range(n):\n",
    "    c[i] = a[i] + b[i]\n",
    "'%.5f sec' % timer.stop()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "E34E4B0CA99A4623800E67A2AC17BD77",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "另外是使用torch来将两个向量直接做矢量加法："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "id": "3B1D700494F847EF88440F3E116DBEFE",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'0.00025 sec'"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "timer.start()\n",
    "d = a + b\n",
    "'%.5f sec' % timer.stop()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "092CF5B75B5B4CCD93BB4AB81604EEDA",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "结果很明显,后者比前者运算速度更快。因此，我们应该尽可能采用矢量计算，以提升计算效率。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "D807B61490E341C0AD858C9F0021D9B6",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**# 线性回归模型从零开始的实现**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "id": "DC5CFD7286BC4348A3D717A593C809E4",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.3.0\n"
     ]
    }
   ],
   "source": [
    "# import packages and modules\n",
    "%matplotlib inline\n",
    "import torch\n",
    "from IPython import display\n",
    "from matplotlib import pyplot as plt\n",
    "import numpy as np\n",
    "import random\n",
    "\n",
    "print(torch.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "BD5816391D6343F6A1CA98F5F3719182",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# **生成数据集**\n",
    "使用线性模型来生成数据集，生成一个1000个样本的数据集，下面是用来生成数据的线性关系：\n",
    "\n",
    "price=warea⋅area+wage⋅age+b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "id": "FC1DCC1F7E484173A9D0CA4E52504260",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# set input feature number \n",
    "num_inputs = 2\n",
    "# set example number\n",
    "num_examples = 1000\n",
    "\n",
    "# set true weight and bias in order to generate corresponded label\n",
    "true_w = [2, -3.4]\n",
    "true_b = 4.2\n",
    "\n",
    "features = torch.randn(num_examples, num_inputs,\n",
    "                      dtype=torch.float32)\n",
    "labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b\n",
    "labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()),\n",
    "                       dtype=torch.float32)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "30E1CD0B3B054F8FAE0DACE3BF331F73",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**使用图像来展示生成的数据**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "id": "2E4733602DA94B0E86DD6C4F86827F8E",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<img src=\"https://cdn.kesci.com/rt_upload/2E4733602DA94B0E86DD6C4F86827F8E/q5p3ksk2bw.png\">"
      ],
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.scatter(features[:, 1].numpy(), labels.numpy(), 1);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "56768F4B17A740FB899ABD2BE92CA304",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**读取数据集**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "id": "12513A06E8D442B384F3CBF866B7763D",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def data_iter(batch_size, features, labels):\n",
    "    num_examples = len(features)\n",
    "    indices = list(range(num_examples))\n",
    "    random.shuffle(indices)  # random read 10 samples\n",
    "    for i in range(0, num_examples, batch_size):\n",
    "        j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) # the last time may be not enough for a whole batch\n",
    "        yield  features.index_select(0, j), labels.index_select(0, j)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true,
    "id": "003DA7290F164E778F4D6BBBB6B365F1",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[-1.1140,  0.5455],\n",
      "        [-1.4256, -0.6059],\n",
      "        [-1.4607, -1.9494],\n",
      "        [-0.5994, -0.1880],\n",
      "        [ 0.7365,  0.0073],\n",
      "        [ 0.1444, -0.0172],\n",
      "        [ 0.9711,  0.6427],\n",
      "        [-0.4812, -0.5075],\n",
      "        [-1.9952,  0.5035],\n",
      "        [ 0.0730, -0.3543]]) \n",
      " tensor([ 0.1359,  3.4087,  7.9099,  3.6503,  5.6514,  4.5615,  3.9519,  4.9485,\n",
      "        -1.4913,  5.5570])\n"
     ]
    }
   ],
   "source": [
    "batch_size = 10\n",
    "\n",
    "for X, y in data_iter(batch_size, features, labels):\n",
    "    print(X, '\\n', y)\n",
    "    break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "DEFFC248CBAD4E1587BE25F76143AD7B",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**初始化模型参数**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "id": "F577A2329B164B8A832CFD8BF0E36C67",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([0.], requires_grad=True)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "w = torch.tensor(np.random.normal(0, 0.01, (num_inputs, 1)), dtype=torch.float32)\n",
    "b = torch.zeros(1, dtype=torch.float32)\n",
    "\n",
    "w.requires_grad_(requires_grad=True)\n",
    "b.requires_grad_(requires_grad=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "D122799FCF6F4D26B48678B9EEBB86B7",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**定义模型**\n",
    "定义用来训练参数的训练模型：\n",
    "\n",
    "price=warea⋅area+wage⋅age+b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "id": "F12975EA0ABD4A748F85D042F977F5BB",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def linreg(X, w, b):\n",
    "    return torch.mm(X, w) + b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "D8BCD659FE7C47828B759A89650932AF",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**定义损失函数**\n",
    "我们使用的是均方误差损失函数：\n",
    "l(i)(w,b)=12(y^(i)−y(i))2,"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "id": "D2ED94D1B99E422E8425DFEAE6F1459A",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def squared_loss(y_hat, y): \n",
    "    return (y_hat - y.view(y_hat.size())) ** 2 / 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "59F157278AF54EC3A45FF99F0EDFF736",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**定义优化函数**\n",
    "在这里优化函数使用的是小批量随机梯度下降：\n",
    "\n",
    "\t(w,b)←(w,b)−η|B|∑i∈B∂(w,b)l(i)(w,b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "id": "15A4A66A3B6A43C980B83FEC5FF85494",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def sgd(params, lr, batch_size): \n",
    "    for param in params:\n",
    "        param.data -= lr * param.grad / batch_size # ues .data to operate param without gradient track"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "80EDEBDF3A8C425B8127C1736380B4DF",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**训练**\n",
    "当数据集、模型、损失函数和优化函数定义完了之后就可来准备进行模型的训练了。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "id": "012A191152214E488EDEBA62FF16EA73",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, loss 0.029979\n",
      "epoch 2, loss 0.000103\n",
      "epoch 3, loss 0.000048\n",
      "epoch 4, loss 0.000047\n",
      "epoch 5, loss 0.000047\n"
     ]
    }
   ],
   "source": [
    "# super parameters init\n",
    "lr = 0.03\n",
    "num_epochs = 5\n",
    "\n",
    "net = linreg\n",
    "loss = squared_loss\n",
    "\n",
    "# training\n",
    "for epoch in range(num_epochs):  # training repeats num_epochs times\n",
    "    # in each epoch, all the samples in dataset will be used once\n",
    "    \n",
    "    # X is the feature and y is the label of a batch sample\n",
    "    for X, y in data_iter(batch_size, features, labels):\n",
    "        l = loss(net(X, w, b), y).sum()  \n",
    "        # calculate the gradient of batch sample loss \n",
    "        l.backward()  \n",
    "        # using small batch random gradient descent to iter model parameters\n",
    "        sgd([w, b], lr, batch_size)  \n",
    "        # reset parameter gradient\n",
    "        w.grad.data.zero_()\n",
    "        b.grad.data.zero_()\n",
    "    train_l = loss(net(features, w, b), labels)\n",
    "    print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": true,
    "id": "40D74C4CC6EE4D42A210D681A16EA0D2",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(tensor([[ 1.9999],\n",
       "         [-3.3997]], requires_grad=True),\n",
       " [2, -3.4],\n",
       " tensor([4.2005], requires_grad=True),\n",
       " 4.2)"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "w, true_w, b, true_b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "0DE6C6DAE3F6455590B04294810B556D",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**线性回归模型使用pytorch的简洁实现**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "id": "7ECE8BB119DA47BC8CF0C714D3BD3208",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.3.0\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "from torch import nn\n",
    "import numpy as np\n",
    "torch.manual_seed(1)\n",
    "\n",
    "print(torch.__version__)\n",
    "torch.set_default_tensor_type('torch.FloatTensor')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "2625E65096514EE89221FADF52DB7FDF",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**生成数据集**\n",
    "在这里生成数据集跟从零开始的实现中是完全一样的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "id": "484205E0501C4A2F8D109007CE18EAE7",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "num_inputs = 2\n",
    "num_examples = 1000\n",
    "\n",
    "true_w = [2, -3.4]\n",
    "true_b = 4.2\n",
    "\n",
    "features = torch.tensor(np.random.normal(0, 1, (num_examples, num_inputs)), dtype=torch.float)\n",
    "labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b\n",
    "labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6A33583A29EE4335B9C92B71A6BC4AD8",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**读取数据集**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "id": "99F56D11437042018D05D9911266B49D",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import torch.utils.data as Data\n",
    "\n",
    "batch_size = 10\n",
    "\n",
    "# combine featues and labels of dataset\n",
    "dataset = Data.TensorDataset(features, labels)\n",
    "\n",
    "# put dataset into DataLoader\n",
    "data_iter = Data.DataLoader(\n",
    "    dataset=dataset,            # torch TensorDataset format\n",
    "    batch_size=batch_size,      # mini batch size\n",
    "    shuffle=True,               # whether shuffle the data or not\n",
    "    num_workers=2,              # read data in multithreading\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": true,
    "id": "4404B5CB527B450F828E4994A23CF316",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[ 0.8642,  0.3315],\n",
      "        [ 0.3743,  0.4471],\n",
      "        [ 0.5586, -0.7459],\n",
      "        [ 0.9572, -1.3235],\n",
      "        [ 0.0127, -0.9222],\n",
      "        [ 0.0506, -0.2999],\n",
      "        [ 0.2143,  1.2112],\n",
      "        [ 0.8346, -1.1488],\n",
      "        [ 0.9235, -0.3483],\n",
      "        [-0.2125, -1.2105]]) \n",
      " tensor([ 4.7940,  3.4298,  7.8483, 10.6137,  7.3466,  5.3215,  0.5200,  9.7601,\n",
      "         7.2101,  7.8974])\n"
     ]
    }
   ],
   "source": [
    "for X, y in data_iter:\n",
    "    print(X, '\\n', y)\n",
    "    break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "94C6ABDF897C4D36855002DF931D46A7",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**定义模型**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "id": "BA79716ED1444EC48A5B0A489EB2E4F7",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "LinearNet(\n",
      "  (linear): Linear(in_features=2, out_features=1, bias=True)\n",
      ")\n"
     ]
    }
   ],
   "source": [
    "class LinearNet(nn.Module):\n",
    "    def __init__(self, n_feature):\n",
    "        super(LinearNet, self).__init__()      # call father function to init \n",
    "        self.linear = nn.Linear(n_feature, 1)  # function prototype: `torch.nn.Linear(in_features, out_features, bias=True)`\n",
    "\n",
    "    def forward(self, x):\n",
    "        y = self.linear(x)\n",
    "        return y\n",
    "    \n",
    "net = LinearNet(num_inputs)\n",
    "print(net)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "id": "14E82D702BBE4F0D8D93BEAE4D7972F1",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sequential(\n",
      "  (linear): Linear(in_features=2, out_features=1, bias=True)\n",
      ")\n",
      "Linear(in_features=2, out_features=1, bias=True)\n"
     ]
    }
   ],
   "source": [
    "# ways to init a multilayer network\n",
    "# method one\n",
    "net = nn.Sequential(\n",
    "    nn.Linear(num_inputs, 1)\n",
    "    # other layers can be added here\n",
    "    )\n",
    "\n",
    "# method two\n",
    "net = nn.Sequential()\n",
    "net.add_module('linear', nn.Linear(num_inputs, 1))\n",
    "# net.add_module ......\n",
    "\n",
    "# method three\n",
    "from collections import OrderedDict\n",
    "net = nn.Sequential(OrderedDict([\n",
    "          ('linear', nn.Linear(num_inputs, 1))\n",
    "          # ......\n",
    "        ]))\n",
    "\n",
    "print(net)\n",
    "print(net[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "C86D77AABBFE4474BD0EDBEB976C653C",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**初始化模型参数**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "id": "C3FAA38A24804DF2860DBC7088857A5F",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Parameter containing:\n",
       "tensor([0.], requires_grad=True)"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from torch.nn import init\n",
    "\n",
    "init.normal_(net[0].weight, mean=0.0, std=0.01)\n",
    "init.constant_(net[0].bias, val=0.0)  # or you can use `net[0].bias.data.fill_(0)` to modify it directly"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "id": "1BA57D4387E14DC18FC25811D6222595",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Parameter containing:\n",
      "tensor([[-0.0142, -0.0161]], requires_grad=True)\n",
      "Parameter containing:\n",
      "tensor([0.], requires_grad=True)\n"
     ]
    }
   ],
   "source": [
    "for param in net.parameters():\n",
    "    print(param)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "C832E6B1D767414C83073A7DC8225934",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**定义损失函数**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "id": "60239B43C4F449848875EE09493DEA10",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "loss = nn.MSELoss()    # nn built-in squared loss function\n",
    "                       # function prototype: `torch.nn.MSELoss(size_average=None, reduce=None, reduction='mean')`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "72AB07768C144A47823EB718C1DAD5F2",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**定义优化函数**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "id": "7997C3590495402E8FF39651C4132937",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SGD (\n",
      "Parameter Group 0\n",
      "    dampening: 0\n",
      "    lr: 0.03\n",
      "    momentum: 0\n",
      "    nesterov: False\n",
      "    weight_decay: 0\n",
      ")\n"
     ]
    }
   ],
   "source": [
    "import torch.optim as optim\n",
    "\n",
    "optimizer = optim.SGD(net.parameters(), lr=0.03)   # built-in random gradient descent function\n",
    "print(optimizer)  # function prototype: `torch.optim.SGD(params, lr=, momentum=0, dampening=0, weight_decay=0, nesterov=False)`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4124DF01E9B64EEA897E252DD296C043",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "**训练**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "id": "584EA3E389454435835FBEC15577F4E9",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, loss: 0.000178\n",
      "epoch 2, loss: 0.000136\n",
      "epoch 3, loss: 0.000043\n"
     ]
    }
   ],
   "source": [
    "num_epochs = 3\n",
    "for epoch in range(1, num_epochs + 1):\n",
    "    for X, y in data_iter:\n",
    "        output = net(X)\n",
    "        l = loss(output, y.view(-1, 1))\n",
    "        optimizer.zero_grad() # reset gradient, equal to net.zero_grad()\n",
    "        l.backward()\n",
    "        optimizer.step()\n",
    "    print('epoch %d, loss: %f' % (epoch, l.item()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "id": "C30EAAB0AC0C4FD3AEC2F858D9C62449",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, -3.4] tensor([[ 1.9999, -3.4010]])\n",
      "4.2 tensor([4.2009])\n"
     ]
    }
   ],
   "source": [
    "# result comparision\n",
    "dense = net[0]\n",
    "print(true_w, dense.weight.data)\n",
    "print(true_b, dense.bias.data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4ED8388CE6B2496EBA89FE2CF4518A9E",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# 两种实现方式的比较\n",
    "从零开始的实现（推荐用来学习）\n",
    "\n",
    "能够更好的理解模型和神经网络底层的原理\n",
    "\n",
    "使用pytorch的简洁实现\n",
    "\n",
    "能够更加快速地完成模型的设计与实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "D9C0E3984FA148FA85B3F7A4C1E354FF",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
